package com.nuanshui.heatedloan.credit.service.third.party;

import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.security.DESC;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.credit.constant.ReturnClientStatus;
import com.nuanshui.heatedloan.credit.constant.SesameAuthResult;
import com.nuanshui.heatedloan.credit.dal.mapper.OptionalAuthMapper;
import com.nuanshui.heatedloan.credit.facade.CustomerIdCardInfoService;
import com.nuanshui.heatedloan.credit.facade.third.party.RiskManagerInteractionService;
import com.nuanshui.heatedloan.credit.facade.third.party.SesameCreditAuthService;
import com.nuanshui.heatedloan.credit.form.CustomerSesameCreditInfoForm;
import com.nuanshui.heatedloan.credit.request.SesameAuthRequest;
import com.nuanshui.heatedloan.credit.response.RiskResponse;
import com.nuanshui.heatedloan.credit.response.SesameAuthResponse;
import com.nuanshui.heatedloan.credit.vo.CustomerIdCardInfoVO;
import com.nuanshui.heatedloan.credit.vo.CustomerSesameCreditInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangxw on 2017/6/30.
 */

@Service(ServiceConstant.SESAMECREDITAUTHSERVICE)
@Transactional(readOnly=true,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
public class SesameCreditAuthServiceImpl extends CommonServiceImpl implements SesameCreditAuthService {

    @Autowired
    private OptionalAuthMapper optionalAuthMapper;

    @Autowired
    private CustomerIdCardInfoService customerIdCardInfoService;

    @Autowired
    private RiskManagerInteractionService riskManagerInteractionService;

    private  static  final Logger logger= LoggerFactory.getLogger(SesameCreditAuthServiceImpl.class);


    @Transactional(readOnly=false,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
    public Map<String,Object> sesameCreditAuth(CustomerSesameCreditInfoForm customerSesameCreditInfoForm){
       //如果已经认证了，直接返回
        Map<String,Object> map=new HashMap<String,Object>();
        CustomerSesameCreditInfoVO customerSesameCreditInfoVO=this.loadVOByUserId(customerSesameCreditInfoForm.getUserId());
        if(customerSesameCreditInfoVO!=null&& SesameAuthResult.AUTHSUCCESS.equals(customerSesameCreditInfoVO.getAuthFlag())){
            map.put("code","00");
            return map;
        }
        map=this.sesameCreditAuthByThirdParty(customerSesameCreditInfoForm);
        //把数据插入数据库中
        customerSesameCreditInfoForm.setAuthFlag(SesameAuthResult.AUTHING);
        customerSesameCreditInfoForm.setStatus(1);
        if(customerSesameCreditInfoVO!=null){
          this.updateSesameStatus(0,customerSesameCreditInfoForm.getUserId());
        }
        this.save(customerSesameCreditInfoForm);
        return map;
    }

    public Map<String,Object> sesameCreditAuthByThirdParty(CustomerSesameCreditInfoForm customerSesameCreditInfoForm){
        Map<String,Object> map=new HashMap<String,Object>();
        logger.info("======================开始进行芝麻信用认证==================：\n");
        //根据之前的认证的信息获取身份证号和名字
        CustomerIdCardInfoVO customerIdCardInfoVO=customerIdCardInfoService.loadByUserId(customerSesameCreditInfoForm.getUserId());
        String customName=customerIdCardInfoVO.getCustomerName();   //用户的名称
        String customIdCard=customerIdCardInfoVO.getIdCard();      //用户的身份证号码
        SesameAuthRequest sesameAuthRequest=new SesameAuthRequest();
        sesameAuthRequest.setCustomerId(customerSesameCreditInfoForm.getUserId());
        sesameAuthRequest.setCustomerIdCard(DESC.decrypt3DES(customIdCard));
        sesameAuthRequest.setCustomerName(customName);
        SesameAuthResponse sesameAuthResponse=riskManagerInteractionService.sesameAuth(sesameAuthRequest);
        //发送http请求
        if(sesameAuthResponse!=null&&sesameAuthResponse.getAuthURL()!=null){
            map.put("url",sesameAuthResponse.getAuthURL());
        }
        logger.info("======================芝麻验证结束======================：\n");
        return map;
    }

    @Transactional(readOnly=false,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
    public void save(CustomerSesameCreditInfoForm customerSesameCreditInfoForm) {
        optionalAuthMapper.saveCustomerSesameCreditInfo(customerSesameCreditInfoForm);
    }

    @Transactional(readOnly=false,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
    public void updateCustomerSesameCreditInfo(CustomerSesameCreditInfoForm customerSesameCreditInfoForm) {
        optionalAuthMapper.updateCustomerSesameCreditInfo(customerSesameCreditInfoForm);
    }

    public CustomerSesameCreditInfoVO loadVOByUserId(String userId){
        return optionalAuthMapper.loadCustomerSesameCreditInfoVOByUserId(userId);
    }

    @Transactional(readOnly=false,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
    public void getSesameCreditAuthCallBack( RiskResponse riskResponse){
        riskManagerInteractionService.callBackSesame(riskResponse);
        CustomerSesameCreditInfoVO customerSesameCreditInfoVO=this.loadVOByUserId(riskResponse.getCustomerId());
        String resultCode=riskResponse.getResultCode();
        String authFlag;
        int status;
        //认证成功
        if(ReturnClientStatus.SUCCESS.equals(resultCode)){
            authFlag=SesameAuthResult.AUTHSUCCESS;
            status=1;
        }
        //认证失败
        else{
            authFlag=SesameAuthResult.AUTHFAIL;
            status=0;
        }
        CustomerSesameCreditInfoForm customerSesameCreditInfoForm=new CustomerSesameCreditInfoForm();
        customerSesameCreditInfoForm.setId(customerSesameCreditInfoVO.getId());
        customerSesameCreditInfoForm.setAuthFlag(authFlag);
        customerSesameCreditInfoForm.setStatus(status);
        this.updateCustomerSesameCreditInfo(customerSesameCreditInfoForm);
    }
    @Transactional(readOnly=false,value= TransactionManagerType.CREDIT_TRANSACTION_MANAGER)
    public void updateSesameStatus(int status,String userId){
        optionalAuthMapper.updateSesameStatus(0,userId);
    }
}
